<template>
	<hm-layout :page-info="{ toolId, name: pageConfig.tool_name, desc: pageConfig.tool_desc }">

		<view class="live-tool">
			<view class="live-area" :style="{ background: bgColor }">
				<NoticeBar :text="noticeText" :color="titleColor" :bg="titleBg"></NoticeBar>
				<image v-show="!showSwiper" class="live-swiper" :src="currentImg" mode="scaleToFill"></image>
				<el-carousel :loop="true" v-show="showSwiper" indicator-position="none"
					class="live-swiper" height="500px" :interval="1500">
					<el-carousel-item class="live-swiper-item" v-for="img in options.slice(0, 10)" :key="img">
						<image class="live-swiper-item" :src="img.url" mode="scaleToFill"></image>
					</el-carousel-item>
				</el-carousel>
				<view class="watermark live-swiper-item" v-if="!isVip || isShowWatermask">
					<image src="https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/haimi-ai/watermark.png" mode="widthFix" style="width: 100%;"></image>
				</view>
			</view>
			<view>
				<el-form label-position="left" class="operation-area" label-width="120px">
					<el-form-item class="color-picker" label="直播区背景色">
						<el-color-picker v-model="bgColor" size="large" />
					</el-form-item>
					<el-form-item class="color-picker" label="标题字体色">
						<el-color-picker v-model="titleColor" size="large" />
					</el-form-item>

					<el-form-item class="color-picker" label="标题文案">
						<el-input v-model="noticeText" placeholder="输入图片名称" />
					</el-form-item>
					
					<el-form-item label="更换图库">
						<el-select v-model="currentCategory" class="m-2" placeholder="选择更换的图库" size="large" @change="getImages">
						    <el-option
						      v-for="item in categories"
						      :key="item.value"
						      :label="item.label"
						      :value="item.value"
						    />
						  </el-select>
					</el-form-item>
					
					<el-form-item class="query-input" label="图片名称">
						<view class="query-operate">
							<el-input style="width: 120px;" v-model="currentImgName" placeholder="输入图片名称" />
							<el-button style="margin-left: 10px;" type="danger" @click="queryImg">查询</el-button>
              <el-button type="success" v-if="!isVip" @click="handleWatermask">去水印</el-button>
              <el-button type="primary" @click="viewTutorial">教程</el-button>
						</view>
					</el-form-item>
						
					<view class="live-preview-list">
						<image class="live-preview-img" v-for="img in currentImgList" :key="img" :src="img.url" mode="widthFix"
							@click="changeCurrentImg(img)">
						</image>
					</view>

					<view class="operation">
						<!-- <el-button type="success" size="large"
							@click="showSwiperTrigger">{{ !showSwiper ? '恢复轮播' : '切换至图片' }}</el-button> -->
						<!-- <el-button type="success" size="large" @click="handleWatermask">{{isShowWatermask ? '去水印' : '显示水印'}}</el-button> -->
					<!-- 	<EditDialog btnText="查看视频教学" width="70%" :isHandleButton="true">
              <video style="width: 100%;height: 600px;"
                src="https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/haimi-ai/live-learn.mp4"></video>
            </EditDialog> -->
					</view>
				</el-form>
				<view class="live-qrcode-contain">
					<view class="live-qrcode">
						<text>1.直播助手下载：</text>
						<qrcode-vue id="app-code" class="app live-qrcode-img" :value="appQrcode" :size="200" level="H" />
					</view>
					<view class="live-qrcode">
						<text>2.浏览器扫码投屏到手机：</text>
						<qrcode-vue v-if="isShowQrcode" class="preview-code live-qrcode-img" :value="previewUrl" :size="200" level="H" />
					</view>
					<view class="live-qrcode">
						<text>3.微信扫码加入交流群</text>
						<qrcode-vue id="service" class="live-qrcode-img service" value="https://mp-f94b3c95-ea57-45eb-aad5-8365caef5925.cdn.bspapp.com/avatar-client/images/service_qrcode.png" :size="200" level="H" />
					</view>
				</view>
			</view>
		</view>
	</hm-layout>
	<VipPopup @paysuccess="paySuccess" :config="pageConfig.price_config"
		:tool-info="{ name: pageConfig.tool_name, desc: pageConfig.tool_desc }" :tool-id="toolId" v-model="vipIsShow" />
</template>

<script setup lang="ts">
	import { ref, onMounted, watchEffect, watch, computed } from "vue";
	import { onLoad } from '@dcloudio/uni-app';
	import { ElNotification } from 'element-plus';
	import VipPopup from '@/common/components/hm-vip-popup/index.vue';
	import NoticeBar from '@/common/components/hm-notice-bar/index.vue';
	import QrcodeVue from 'qrcode.vue'
	import EditDialog from '@/common/components/EditDialog/index.vue'
	import shortid from 'shortid'

	const defaultOptions = [
		{
			name: '仲',
			url: 'https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/2023/11/27/51508957-37552914-0.png'
		},
		{
			name: '庄',
			url: 'https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/2023/11/27/51494528-33172488-0.png'
		},
		{
			name: '板',
			url: 'https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/2023/11/27/51486144-71324863-0.png'
		},
		{
			name: '狄',
			url: 'https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/2023/11/27/51480606-59247721-0.png'
		},
		{
			name: '初',
			url: 'https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/2023/11/27/51450136-29863884-0.png'
		}
	]

	const vk = uni.vk;
	const toolId = 'ai_live';
	// const id = uni.getPushClientId();

	const noticeText = ref('你留姓氏，我来作图')

	const bgColor = ref("#ffffff");
	const titleBg = ref("transparent");
	const titleColor = ref("#000000");
	
	const appQrcode = 'https://mp-c3603e48-468f-4859-9888-0b616ac21d6c.cdn.bspapp.com/apk/live.apk';

	const isShowQrcode = ref(true);
	const refleshQrcode = () => {
		isShowQrcode.value = false;
		setTimeout(() => {
			ElNotification({
				title: '温馨提示',
				message: '每次修改直播样式后，记得重新扫描投屏二维码哦！',
				type: 'info',
			})
			isShowQrcode.value = true;
		}, 300)
	}
	const previewUrl = computed(() => {
		let url = `https://haimi-ai-1302621554.cos.ap-nanjing.myqcloud.com/AI/index.html#/pages/lh/lh?d=${
		  push_clientid.value
		}`
		console.log(url)
		return  url;
	})
	
	const currentImg = ref(defaultOptions[0].url);
	const currentImgName = ref('');
	const options = ref(defaultOptions);
	const currentImgList = ref([]);
	const showSwiper = ref(false);
	let isVip = ref(false)

	const pageConfig = ref({
		tool_name: "AI头像直播工具",
		tool_desc: "告别PS手工切换，助您高效直播!",
		price_config: []
	})
	
	let push_clientid = ref('');
	// 初始化消息id
	const getPushId = () => {
		push_clientid.value = shortid.generate();
		// uni.getPushClientId({
		// 	success: (res) => {
		// 		push_clientid.value = res.cid
		// 		console.log('客户端推送标识:',push_clientid.value)
		// 	},
		// 	fail(err) {
		// 		console.log(err)
		// 	}
		// })
	}
	onLoad(async () => {
		getPushId();
		vk.callFunction({
			url: 'ai-client/common/pub/getConfig',
			title: '请求中...',
			data: {},
			success: (res) => {
				const toolConfig = res.data.find(conf => conf.tool_id === toolId);
				pageConfig.value = toolConfig || {};
			}
		});
		
		getCategories();
		const pages = getCurrentPages();
		const page = pages[pages.length - 1];
		const eventChannel = page.getOpenerEventChannel();
		eventChannel.on('data', (data) => {
			console.warn('eventChannel');
			if (data) {
				getImages(data._id);
				currentCategory.value = data._id;
			}
		})
		
		isVip.value = await checkVip();
        isShowWatermask.value = !isVip.value
	})
	
	// 当前选中的图库
	const currentCategory = ref(null);
	// 图库列表
	const categories = ref([])
	
	// 请求当前用户的图库列表
	const getCategories = () => {
		vk.callFunction({
			url: "client/uni-id-files/categories/kh/getList",
			loading: true,
			data: {},
			success: function(data) {
				if (data?.rows?.length) {
					categories.value = data.rows.map(item => ({ label: item.name, value: item._id }))
				} else {
					// vk.toast('未查询到图片');
				}
			}
		});
	}
	
	// 图库请求默认参数
	const queryImageFormData = {
		columns: [
		    {
		        "key": "display_name",
		        "title": "名称",
		        "type": "text",
		        "mode": "%%"
		    },
		    {
		        "key": "url",
		        "title": "URL",
		        "type": "text",
		        "mode": "="
		    },
		    {
		        "key": "category_id",
		        "title": "分类id",
		        "type": "text",
		        "mode": "="
		    },
		    {
		        "key": "type",
		        "title": "文件类型",
		        "type": "text",
		        "mode": "="
		    }
		],
		pageIndex: 1,
		pageSize: 99999,
		formData: {
			category_id: '',
		}
	}
	
	// 请求图库
	const getImages = (category_id) => {
		vk.callFunction({
		  url: "client/uni-id-files/files/kh/getList",
		  loading: true,
		  data: {
				...queryImageFormData,
				formData: { category_id }
			},
		  success: function(data) {
				let reg = new RegExp(/\.[^/.]+$/ig);
				if (data?.rows?.length) {
					options.value = data.rows.map(item => ({ url: item.url, name: item.display_name.replace(reg, '') }))
          currentImg.value = options.value[0].url
          currentImgList.value = options.value.slice(0, 5);
				} else {
					vk.toast('未查询到图片');
				}
		  }
		});
	}
	
	// 点击选中展示的图片
	const changeCurrentImg = (img) => {
		currentImg.value = img.url;
		currentImgName.value = img.name;
		showSwiper.value = false;
    pushMessage();
	}
	watchEffect(() => {
		window.addEventListener('keydown', (e) => {
			if (e.key === 'Enter') {
				queryImg()
			}
		})
	})
	
	// vip支付回调
	const paySuccess = async () => {
		isVip.value = await checkVip();
	}

	// vip校验
	const vipIsShow = ref(false);
	const showVipPopup = () => {
		vipIsShow.value = true;
	}

	const checkVip = () : Promise<boolean> => {
		return new Promise((resolve, reject) => {
			vk.callFunction({
				url: 'user/kh/getMyToolInfos',
				title: '请求中...',
				data: {},
				success: (res) => {
					const toolInfoList = res.toolInfo;
					if (!toolInfoList || !toolInfoList.length) {
						resolve(false);
					} else {
						// 过滤当前tool_id且未过期
						const tool = toolInfoList.find(item => (item.tool_id === toolId && !item.vipExpire));
						resolve(!!tool);
					}
				},
				fail() {
					resolve(false);
				}
			});
		})
	}
	
	// 是否显示水印
	const isShowWatermask = ref(true);
	const handleWatermask = async () => {
		if (isVip.value) {
			isShowWatermask.value = !isShowWatermask.value;
		} else {
			const checkVipResult = await checkVip();			
			if (!checkVipResult) {
				return showVipPopup();
			}
		}
		pushMessage();
	}
	// 查询图片
	const queryImg = async () => {
		showSwiper.value = false;

		const previewOptions = options.value.filter((item) => {
			return item.name.indexOf(currentImgName.value) > -1 || currentImgName.value.indexOf(item.name) > -1;
		})

		if (!previewOptions || !previewOptions.length) {
			currentImg.value = options.value[0].url;
			return;
		}
		
		currentImg.value = previewOptions[0].url;
		currentImgList.value = previewOptions.slice(0, 5);
		
		pushMessage();
	}

	const showSwiperTrigger = () => {
		if (showSwiper.value && !currentImg.value) {
			ElNotification({
				title: '请查询正确的图片后再切换',
				message: '',
				type: 'error',
			})
			return
		};
		
		showSwiper.value = !showSwiper.value;
		
		if (!showSwiper.value && !currentImg.value) {
			vk.toast('未查询需要展示的图片');
			return;
		}
		!showSwiper.value && pushMessage();
	}
	
	const pushMessage = async () => {
		vk.callFunction({
			url: 'client/push/kh/sendLiveChange',
			title: 'loading...',
			data: {
				push_clientid: push_clientid.value,
				img: currentImg.value,
				watermask: !isVip.value,
				bgColor: bgColor.value,
				titleColor: titleColor.value,
				title: noticeText.value
			},
			success: () => {
				vk.toast('更新成功！');
			}
		});
	}
	
  const viewTutorial = () => {
    window.open("https://xv9glzk1a1f.feishu.cn/docx/JQYcdAdsyolWPrxuLJKcWaWunbd")
  }
  uni.onPushMessage((res) => {
    console.log("收到推送消息：",res) //监听推送消息
  })
</script>
<style lang="less" scoped>
	.live-tool {
		display: flex;
	}

	.live-area {
		margin: 10px 0 0 10px;
		display: flex;
		flex-direction: column;
		position: relative;
		border: 1px solid #ddd;
		padding: 20px;
		height: 100%;

		.watermark {
			position: absolute;
			left: 20px;
			top: 70px;
			opacity: 0.5;
		}
	}

	.live-preview-list {
		display: flex;
		width: 500px;
		margin-top: 10px;
		justify-content: space-between;
		height: 90px;
		overflow-y: hidden;

		.live-preview-img {
			width: 90px;
		}
	}

	.live-swiper {
		width: 500px;
		height: 500px;
	}

	.live-swiper-item {
		width: 500px;
		height: 500px;
	}

	.operation-area {
		display: flex;
		flex-direction: column;
		padding: 10px;
	}

	.operation {
		display: flex;
		width: 500px;
		justify-content: center;
		align-items: center;
		margin: 30px 0 0;
		flex-wrap: wrap;
	}

	.live-qrcode-contain {
		display: flex;
    .live-qrcode {
    	width: 100%;
      margin-right: 15px;
    	display: flex;
    	flex-direction: column;
    	align-items: center;
    	min-height: 250px;
    }
	}

	.preview-code {
		width: 250px;
	}

	.live-qrcode-img {
		margin-top: 10px;
		margin-left: 5px;
		min-height: 200px;
	}

	.uploader {
		width: 100px;
		margin-left: 10px;
	}

	.query-input {
		width: 300px;
		margin: 0;
	}

	.query-operate {
		display: flex;
	}

	.color-picker {
		// width: 300px;
	}

	.info {
		padding: 10px;
		display: flex;
		flex-direction: column;

		.info-item {
			margin: 5px 0;
		}

		.statement {
			:deep(.el-alert__content) {
				text-align: center;
			}

			:deep(.el-alert__title) {
				font-size: 16px !important;
			}

			:deep(.el-alert__description) {
				font-size: 14px !important;
				width: 440px;
			}
		}

	}
</style>